/**
 * 
 */
package com.lu.service.impl;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import com.lu.service.IMessageHandleService;

/**
 * @author lusm
 *
 * @Date 2016年5月8日
 */
@Service("webSocketService")
@ServerEndpoint(value = "/hello", configurator = SpringConfigurator.class)
public class WebSocketService {
	private Logger logger = Logger.getLogger(WebSocketService.class);
	@Resource
	private IMessageHandleService messageHandleService;
	// private static Map<String, WebSocketService> map = new
	// ConcurrentHashMap<String, WebSocketService>();
	private static int count = 0;
	private Session session;

	@OnOpen
	public void open(Session session) {
		this.session = session;
		count++;
		logger.info("一个人上线，当前人数" + count);
		session.getAsyncRemote().sendText("hello");
	}

	@OnClose
	public void close(Session session) {
		count--;
		logger.info("一个人下线，当前人数" + count);
	}

	@OnError
	public void onError(Throwable error) {
		logger.error("websocket出错", error);
	}

	@OnMessage
	public void handleMessage(String message, Session session) {
		messageHandleService.addSufix(message);
		this.sendMessage(message);
		logger.info("收到一条消息");
	}

	public void sendMessage(String message) {
		this.session.getAsyncRemote().sendText(message);
	}

}
